#include "BingWallpaperService.h"
#include "ConfigHelper.h"
#include "FileHelper.h"
#include "HttpClient.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>

#include <QDateTime>
#include <QMovie>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),countPerPage(4)
{
    ui->setupUi(this);
    this->InitialUI();
    this->InitData();
    this->InitialSlot();
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    this->painter = new QPainter(this);
    if(pixmap->isNull())
    {
        pixmap->load("background.jpg");
    }
    QPixmap tmp = pixmap->scaled(800,480);
    painter->drawPixmap(0,0,800,480,tmp);
    QWidget::paintEvent(event);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitData()
{
    qDebug()<<"InitData...";
    pixmap = new QPixmap();
    service = new WallpaperService();
    httpClient = new HttpClient();
    currentPage = 1;
    nextStart = false;
    service->GetBingWallpapersAsync(currentPage++,countPerPage);
    currentIndex = 0;
}

//获取壁纸槽函数
void MainWindow::GetWallpaperFinished(QList<WallpaperModel *> papers)
{
    qDebug()<<"MainWindow::GetWallpaperFinished papers.size()"<<papers.size();
    SaveImageList(papers);
    for(int i=0;i<papers.size();i++)
    {
        this->papers.append(papers.at(i));
    }

    if(papers.size()>0 && currentIndex < papers.size())
    {
        this->currentPaper = papers.at(currentIndex);

        SetWidgetImage(currentIndex);
    }
    else
    {
        currentImageName = "background.jpg";
    }
}

void MainWindow::SetWidgetImage(int index)
{
    int count = papers.size();
    if(count==0)
    {
        qDebug()<<"SetWidgetImage papers.size() "<<count;
        return;
    }
    if(index<0)
    {
        index = 0;
        qDebug()<<"Exceuse me? index < 0?";
    }
    else if(index >= count)
    {
        QList<WallpaperModel*> tmp = service->GetBingWallpapers(currentPage++,countPerPage);
        if(tmp.empty())
        {
            return;
        }
        for(int i=0;i<tmp.size();i++)
        {
            this->papers.append(tmp.at(i));
        }
    }
    QString name = papers.at(index)->Hash+".jpg";
    QDir imageCache(QDir::currentPath().append("/imageCache/"));
    if(imageCache.exists(name))
    {
        this->pixmap->load(name);
        this->currentImageName = name;
    }
    else
    {
        httpClient->GetImageAsync(papers.at(index)->Url,papers.at(index)->Hash+".jpg");
    }
}

void MainWindow::SaveImageList(QList<WallpaperModel *> papers)
{
    fileHelper.CreateFolder("imageCache",QDir::currentPath());

    for(int i =0;i<papers.size();i++)
    {
        fileHelper.AppendText("history.txt",papers.at(i)->Hash+".jpg");
    }
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        moveStart = true;
        this->preMousePos = event->globalPos();
        //qDebug()<<"Left Button x:"<<preMousePos.x()<<" y:"<<preMousePos.y();
        event->ignore();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(moveStart)
    {
        QPoint tmpPos = event->globalPos()- this->preMousePos;
        this->move(this->pos() + tmpPos);
    }
     this->preMousePos = event->globalPos();
    event->ignore();
}

void MainWindow::mouseReleaseEvent(QMouseEvent *)
{
    moveStart = false;
}

void MainWindow::InitialUI()
{
    setObjectName("mainWindow");
    //setStyleSheet("#mainWindow {border-image:url(:/image/background.jpg);}");
    setWindowFlags(Qt::FramelessWindowHint);
    setMinimumHeight(480);
    setMinimumWidth(800);

    ui->buttonSetting->setStyleSheet
     ("QPushButton{border-image: url(:/image/Settings.png);}"
     "QPushButton:hover{border-image: url(:/image/Settings_press.png);}"
     "QPushButton:pressed{border-image: url(:/image/Settings.png);}");
     ui->buttonMinsize->setStyleSheet
     ("QPushButton{border-image: url(:/image/minimize.png);}"
      "QPushButton:hover{border-image: url(:/image/minimize_press.png);}"
      "QPushButton:pressed{border-image: url(:/image/minimize.png);}");
    ui->buttonClose->setStyleSheet
    ("QPushButton{border-image: url(:/image/close.png);}"
    "QPushButton:hover{border-image: url(:/image/button_close_press.png);}"
    "QPushButton:pressed{border-image: url(:/image/close.png);}");
    ui->leftButton->setStyleSheet
    (""
    "QPushButton:hover{border-image: url(:/image/arrowLeft_press.png);}"
    "QPushButton:pressed{border-image: url(:/image/arrowLeft.png);}");
    //"QPushButton{border-image: url(:/image/arrowLeft.png);}"
    ui->leftButton->setFlat(true);

    ui->rightButton->setStyleSheet
    (
    "QPushButton:hover{border-image: url(:/image/arrowRight_press.png);}"
    "QPushButton:pressed{border-image: url(:/image/arrowRight.png);}");
    //"QPushButton{border-image: url(:/image/arrowRight.png);}"
    ui->rightButton->setFlat(true);

    ui->pushButtonBing->setFlat(true);
    ui->pushButtonBing->setStyleSheet("QPushButton{color:rgb(255,255,255)}"
                                      "QPushButton{border:hidden}"
                                      "QPushButton:hover{color:rgb(220,220,220)}"
                                      "QPushButton:pressed{color:rgb(255,255,255)}"
                                      );

}

void MainWindow::InitialSlot()
{
    QObject::connect(ui->buttonClose,SIGNAL(clicked(bool)),qApp,SLOT(quit()));
    QObject::connect(ui->buttonMinsize,SIGNAL(clicked(bool)),this,SLOT(MiniMized()));
    QObject::connect(ui->leftButton,SIGNAL(clicked(bool)),this,SLOT(Previous()));
    QObject::connect(ui->rightButton,SIGNAL(clicked(bool)),this,SLOT(Next()));
    QObject::connect(ui->pushButtonBing,SIGNAL(clicked(bool)),this,SLOT(SetAsWallpaper()));
    QObject::connect(service,SIGNAL(GetBingWallpapersFinish(QList<WallpaperModel*>)),
                     this,SLOT(GetWallpaperFinished(QList<WallpaperModel*>)));
    QObject::connect(httpClient,SIGNAL(GetImageFinished(QNetworkReply*,QString)),
                     this,SLOT(DownloadImageFinish(QNetworkReply*,QString)));
//    QObject::connect(httpClient,SIGNAL(GetByteArrayFinished(QNetworkReply*)),
//                     this,SLOT(DownloadImageFinish(QNetworkReply*)));
}

void MainWindow::Previous()
{
    currentIndex--;
    SetWidgetImage(currentIndex);
    qDebug()<<"Previous";
    repaint();
}

void MainWindow::Next()
{

    currentIndex++;
    SetWidgetImage(currentIndex);
    qDebug()<<"Next ";
    repaint();


}

void MainWindow::SetAsWallpaper()
{
    WindowsServiceHelper::SetDesktopWallpaper(currentImageName);
}

//图片下载槽函数
void MainWindow::DownloadImageFinish(QNetworkReply *reply,QString fileName)
{
    qDebug() << "DownloadImage finished ..."<<fileName;
    if(reply->error() == QNetworkReply::NoError)
    {
        pixmap->loadFromData(reply->readAll());

        if(pixmap->save("imageCache/"+fileName))
        {
            currentImageName = fileName;
            qDebug() << "picture saved as " << currentImageName;
        }
    }
    else
    {
        qDebug() << reply->errorString();
    }
    repaint();
}
